package com.tcfvic.client.panels.widgets;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.tcfvic.client.PersonService;
import com.tcfvic.client.PersonServiceAsync;
import com.tcfvic.client.panels.widgets.addons.advancedtable.AdvancedTable;
import com.tcfvic.client.panels.widgets.addons.advancedtable.RowSelectionListener;
import com.tcfvic.client.pojos.Workercompany;
import com.tcfvic.client.tools.Month;
import com.tcfvic.client.tools.State;
import com.tcfvic.client.tools.Tools;

public class CompanyDetailsInputWidget extends FlexTable implements
		RowSelectionListener {
	private TextBox companyId = new TextBox();
	private TextBox nameTextBox = new TextBox();
	private TextBox brandTextBox = new TextBox();
	private TextBox siteTextBox = new TextBox();
//	private TextBox divisionTextBox = new TextBox();
	private TextBox streetLine1 = new TextBox();
//	private TextBox streetLine2 = new TextBox();
	private TextBox suburb = new TextBox();
	private ListBox state = null;
	private TextBox postcode = new TextBox();
	private TextBox phone = new TextBox();
	private TextBox contact = new TextBox();
	private TextBox contactPosition = new TextBox();
	private TextBox contactTel1 = new TextBox();
	private TextBox contactTel2 = new TextBox();
	private TextBox contactEmail = new TextBox();
	
	private ListBox dayClosure = null;
	private ListBox monthClosure = null;
	private ListBox yearClosure = null;
//	private ListBox dayProdStop = null;
//	private ListBox monthProdStop = null;
//	private ListBox yearProdStop = null;
	private TextArea closureReason = new TextArea();
	private CompanyDetailsListWidget list = null;

	/**
	 * Create a remote service proxy to talk to the server-side CompanyDetails
	 * service.
	 */
	private final PersonServiceAsync personService = GWT
			.create(PersonService.class);

	public CompanyDetailsInputWidget() {
		super();

		// Create a table to layout the form options
		setCellSpacing(4);
		setWidth("100%");
		FlexCellFormatter cellFormatter = getFlexCellFormatter();

		// Add a title to the form
		setHTML(0, 0, "Add/Edit company data");
		cellFormatter.setColSpan(0, 0, 4);
		cellFormatter.setHorizontalAlignment(0, 0,
				HasHorizontalAlignment.ALIGN_CENTER);
		int row = 1;
		// Add some standard form options
		setHTML(row, 0, "Company name");
		setWidget(row++, 1, nameTextBox);
		setHTML(row, 0, "Brand");
		setWidget(row++, 1, brandTextBox);
		setHTML(row, 0, "Site");
		setWidget(row++, 1, siteTextBox);
//		setHTML(row, 0, "Division");
//		setWidget(row++, 1, divisionTextBox);

		setHTML(row, 0, "Street");
		setWidget(row++, 1, streetLine1);
//		setHTML(row, 0, "Street line 2");
//		setWidget(row++, 1, streetLine2);
		setHTML(row, 0, "Suburb");
		setWidget(row++, 1, suburb);
		setHTML(row, 0, "State");
		state = Tools.getStatesListBox();
		setWidget(row++, 1, state);
		setHTML(row, 0, "Postcode");
		setWidget(row++, 1, postcode);
		setHTML(row, 0, "Company phone");
		setWidget(row++, 1, phone);

		cellFormatter.setColSpan(row, 1, 3);


		int row2 = 1;
		HorizontalPanel hp = new HorizontalPanel();
		dayClosure = Tools.getDayListBox();
		monthClosure = Tools.getMonthListBox();
		yearClosure = Tools.getYearListBox();
		hp.add(dayClosure);
		hp.add(monthClosure);
		hp.add(yearClosure);
		setHTML(row2, 2, "Site closure date<br>(if applicable)");
		setWidget(row2++, 3, hp);

//		hp = new HorizontalPanel();
//		dayProdStop = Tools.getDayListBox();
//		monthProdStop = Tools.getMonthListBox();
//		yearProdStop = Tools.getYearListBox();
//		hp.add(dayProdStop);
//		hp.add(monthProdStop);
//		hp.add(yearProdStop);
//		setHTML(row2, 2, "Date production stopped");
//		setWidget(row2++, 3, hp);

		setHTML(row2, 2, "Company contact");
		setWidget(row2++, 3, contact);
		setHTML(row2, 2, "Contact position");
		setWidget(row2++, 3, contactPosition);
		setHTML(row2, 2, "Contact phone");
		setWidget(row2++, 3, contactTel1);
		setHTML(row2, 2, "Contact mobile");
		setWidget(row2++, 3, contactTel2);
		setHTML(row2, 2, "Contact email");
		setWidget(row2++, 3, contactEmail);

		cellFormatter.setRowSpan(row2, 2, 4);
		cellFormatter.setRowSpan(row2, 3, 4);
		closureReason.setVisibleLines(7);
		setHTML(row2, 2, "Closure reason/details");
		setWidget(row2++, 3, closureReason);

		final Button saveButton = new Button("Save");
		saveButton.getElement().setId("saveButton");
		setWidget(row, 4, saveButton);

		// Add a handler to close the DialogBox
		saveButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				saveCompanyDetails();
			}
		});
		
		clearAllFields();
	}

	public void addCompanyDetailsList(CompanyDetailsListWidget list) {
		this.list = list;
	}

	private boolean validInput() {
		if (companyId.getText() != null
				&& companyId.getText().trim().equals("-1")) {
			new SimpleMessagePopup(
					"Please select or create a new company before saving",
					null).showPopup();
			return false;
		}
		try {
			if (postcode.getText() != null
					&& postcode.getText().trim().length() > 0) {
				Integer.parseInt(postcode.getText());
			}

		} catch (Exception e) {
			new SimpleMessagePopup("Please enter a valid 4 digit postcode",
					postcode).showPopup();
			return false;
		}
		try {
			if (Tools.checkIfSelectedValue(dayClosure, monthClosure,
					yearClosure)
					&& !Tools
							.isValidDate(dayClosure, monthClosure, yearClosure)) {
				throw new Exception();
			}
		} catch (Exception e) {
			System.err.println(e);
			new SimpleMessagePopup("The closure date is not valid", dayClosure)
					.showPopup();
			return false;
		}
//		try {
//			if (Tools.checkIfSelectedValue(dayProdStop, monthProdStop,
//					yearProdStop)
//					&& !Tools.isValidDate(dayProdStop, monthProdStop,
//							yearProdStop)) {
//				throw new Exception();
//			}
//		} catch (Exception e) {
//			System.err.println(e);
//			new SimpleMessagePopup("The production stop date is not valid",
//					dayProdStop).showPopup();
//			return false;
//		}
		return true;
	}

	private boolean minimumInput() {
		if (nameTextBox.getText() == null
				|| nameTextBox.getText().trim().length() == 0) {
			new SimpleMessagePopup("Please enter a company name", nameTextBox)
					.showPopup();
			return false;
		}
		return true;
	}
	
	public void createNewRecord() {
		clearAllFields();
		companyId.setText("");
	}
	
	public void clearAllFields() {
		companyId.setText("-1");
		nameTextBox.setText("");
		brandTextBox.setText("");
		siteTextBox.setText("");
//		divisionTextBox.setText("");
		streetLine1.setText("");
//		streetLine2.setText("");
		suburb.setText("");
		postcode.setText("");
		phone.setText("");
		contact.setText("");
		contactPosition.setText("");
		contactTel1.setText("");
		contactTel2.setText("");
		contactEmail.setText("");
		Tools.resetList(state, dayClosure, monthClosure, yearClosure);
		closureReason.setText("");
	}

	@Override
	public void onRowSelected(AdvancedTable sender, String rowId) {
		clearAllFields();
		personService.getCompanyDetails(Integer.valueOf(rowId),
				new AsyncCallback<Workercompany>() {
					@Override
					public void onSuccess(Workercompany result) {
						companyId.setText(String.valueOf(result.getId()));
						nameTextBox.setText(result.getName());
						brandTextBox.setText(result.getBrand());
						siteTextBox.setText(result.getSite());
//						divisionTextBox.setText(result.getDivision());
						contact.setText(result.getContactperson());
						contactPosition.setText(result.getContactposition());
						contactTel1.setText(result.getContactph1());
						contactTel2.setText(result.getContactph2());
						contactEmail.setText(result.getContactph3());

						streetLine1.setText(result.getAddressline1());
//						streetLine2.setText(result.getAddressline2());
						suburb.setText(result.getSuburb());
						closureReason
								.setText(result.getReasonforredundancies());
						if (result.getState() != null
								&& result.getState().trim().length() > 0) {
							state.setSelectedIndex(State.valueOf(
									result.getState()).getId());
						}
						postcode.setText(result.getPostcode() != null ? result
								.getPostcode().toString() : "");
						phone.setText(result.getPhone());
						if (result.getDateofclosure() != null) {
							dayClosure.setSelectedIndex(Integer.parseInt(Tools
									.getDay(result.getDateofclosure())));
							monthClosure.setSelectedIndex(Month.valueOf(
									Tools.getMonth(result.getDateofclosure())
											.toUpperCase()).getId());
							yearClosure
									.setSelectedIndex(Integer
											.parseInt(Tools.getYear(result
													.getDateofclosure())) - 1899);
						}
//						if (result.getDateproductionstopped() != null) {
//							dayProdStop
//									.setSelectedIndex(Integer
//											.parseInt(Tools
//													.getDay(result
//															.getDateproductionstopped())));
//							monthProdStop.setSelectedIndex(Month.valueOf(
//									Tools.getMonth(
//											result.getDateproductionstopped())
//											.toUpperCase()).getId());
//							yearProdStop
//									.setSelectedIndex(Integer
//											.parseInt(Tools
//													.getYear(result
//															.getDateproductionstopped())) - 1899);
//						}
					}

					@Override
					public void onFailure(Throwable caught) {
						System.err
								.println("Error occured returning the individuals details: "
										+ caught);
						new SimpleMessagePopup(
								"The company's record was not retrieved due to an internal error",
								null).showPopup();
					}
				});
	}

	private void saveCompanyDetails() {
		try {
			if (!validInput() || !minimumInput()) {
				return;
			}

			Workercompany company = new Workercompany();
			if (companyId != null && companyId.getText().trim().length() > 0) {
				company.setId(new Integer(companyId.getText()));
			}

			company.setName(nameTextBox.getText());
			company.setBrand(brandTextBox.getText());
			company.setSite(siteTextBox.getText());
//			company.setDivision(divisionTextBox.getText());
			company.setContactperson(contact.getText());
			company.setContactposition(contactPosition.getText());
			company.setContactph1(contactTel1.getText());
			company.setContactph2(contactTel2.getText());
			company.setContactph3(contactEmail.getText());
			if (Tools.isValidDate(dayClosure, monthClosure, yearClosure)) {
				company.setDateofclosure(Tools.parseDate(dayClosure
						.getItemText(dayClosure.getSelectedIndex())
						+ "/"
						+ Month.valueOf(
								monthClosure.getItemText(monthClosure
										.getSelectedIndex())).getId()
						+ "/"
						+ yearClosure.getItemText(yearClosure
								.getSelectedIndex())));
			}
//			if (Tools.isValidDate(dayProdStop, monthProdStop, yearProdStop)) {
//				company.setDateproductionstopped(Tools.parseDate(dayProdStop
//						.getItemText(dayProdStop.getSelectedIndex())
//						+ "/"
//						+ Month.valueOf(
//								monthProdStop.getItemText(monthProdStop
//										.getSelectedIndex())).getId()
//						+ "/"
//						+ yearProdStop.getItemText(yearProdStop
//								.getSelectedIndex())));
//			}
			company.setAddressline1(streetLine1.getText());
//			company.setAddressline2(streetLine2.getText());
			company.setSuburb(suburb.getText());
			if (state != null && state.getSelectedIndex() > -1) {
				company.setState(state.getItemText(state.getSelectedIndex()));
			}
			if (postcode.getText() != null
					&& postcode.getText().trim().length() > 0) {
				company.setPostcode(new Integer(postcode.getText()));
			}
			company.setPhone(phone.getText());
			company.setReasonforredundancies(closureReason.getText());

			personService.saveCompanyDetails(company,
					new AsyncCallback<Void>() {
						@Override
						public void onSuccess(Void result) {
							System.out
									.println("Successfully wrote company record to dbase");
							clearAllFields();
							if (list != null) {
								list.updateTableData();
							}
							new SimpleMessagePopup(
									"Company saved successfully", null)
									.showPopup();
						}

						@Override
						public void onFailure(Throwable caught) {
							System.err
									.println("Error occured writing company details to database in "
											+ "CompanyDetailsInputWidget.saveCompanyDetail: "
											+ caught);
							new SimpleMessagePopup(
									"The data was not saved due to an internal error",
									null).showPopup();
						}
					});
		} catch (Exception e) {
			new SimpleMessagePopup(
					"An error occured saving the company details: " + e, null)
					.showPopup();
		}
	}

}
